#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据传输诊断脚本
全面诊断WebSocket服务器和客户端连接问题
"""

import asyncio
import websockets
import json
import logging
import socket
import subprocess
import sys
import os
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class DataTransmissionDiagnostic:
    def __init__(self):
        self.server_ip = "172.20.0.94"
        self.server_port = 8080
        self.server_url = f"ws://{self.server_ip}:{self.server_port}"
        
    def check_network_connectivity(self):
        """检查网络连接性"""
        logger.info("=== 网络连接性检查 ===")
        
        # 检查本机IP
        try:
            import subprocess
            result = subprocess.run(['ipconfig'], capture_output=True, text=True, shell=True)
            logger.info("本机网络配置:")
            for line in result.stdout.split('\n'):
                if 'IPv4' in line or 'IP' in line:
                    logger.info(f"  {line.strip()}")
        except Exception as e:
            logger.error(f"获取网络配置失败: {e}")
        
        # 检查端口监听
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            result = sock.connect_ex((self.server_ip, self.server_port))
            sock.close()
            
            if result == 0:
                logger.info(f"✅ 端口 {self.server_port} 可访问")
            else:
                logger.error(f"❌ 端口 {self.server_port} 不可访问")
                return False
        except Exception as e:
            logger.error(f"端口检查失败: {e}")
            return False
        
        return True
    
    async def test_websocket_server(self):
        """测试WebSocket服务器"""
        logger.info("=== WebSocket服务器测试 ===")
        
        try:
            async with websockets.connect(self.server_url) as websocket:
                logger.info("✅ WebSocket连接成功")
                
                # 测试认证消息
                auth_message = {
                    "type": "AUTH",
                    "data": {
                        "userId": "test_user_1",
                        "username": "test_user",
                        "userType": "USER",
                        "department": "测试科室"
                    }
                }
                
                await websocket.send(json.dumps(auth_message))
                logger.info("✅ 认证消息发送成功")
                
                # 等待响应
                try:
                    response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
                    logger.info(f"✅ 收到服务器响应: {response}")
                except asyncio.TimeoutError:
                    logger.warning("⚠️ 等待响应超时")
                
                # 测试患者上报消息
                patient_message = {
                    "type": "PATIENT_REPORT",
                    "data": {
                        "patientId": "12345",
                        "patientName": "测试患者",
                        "reporterName": "测试医生",
                        "department": "内科",
                        "timestamp": datetime.now().isoformat()
                    }
                }
                
                await websocket.send(json.dumps(patient_message))
                logger.info("✅ 患者上报消息发送成功")
                
                # 等待响应
                try:
                    response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
                    logger.info(f"✅ 收到患者上报响应: {response}")
                except asyncio.TimeoutError:
                    logger.warning("⚠️ 等待患者上报响应超时")
                
                return True
                
        except Exception as e:
            logger.error(f"❌ WebSocket连接失败: {e}")
            return False
    
    def check_android_device(self):
        """检查Android设备连接"""
        logger.info("=== Android设备检查 ===")
        
        try:
            # 检查adb是否可用
            result = subprocess.run(['adb', 'version'], capture_output=True, text=True)
            if result.returncode == 0:
                logger.info("✅ ADB工具可用")
            else:
                logger.error("❌ ADB工具不可用")
                return False
            
            # 检查设备连接
            result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
            logger.info("连接的Android设备:")
            logger.info(result.stdout)
            
            if "device" in result.stdout:
                logger.info("✅ 检测到Android设备")
                return True
            else:
                logger.warning("⚠️ 未检测到Android设备")
                return False
                
        except Exception as e:
            logger.error(f"❌ Android设备检查失败: {e}")
            return False
    
    def check_firewall(self):
        """检查防火墙设置"""
        logger.info("=== 防火墙检查 ===")
        
        try:
            # 检查Windows防火墙
            result = subprocess.run(['netsh', 'advfirewall', 'show', 'allprofiles'], 
                                  capture_output=True, text=True, shell=True)
            logger.info("防火墙状态:")
            for line in result.stdout.split('\n'):
                if 'State' in line or 'ON' in line or 'OFF' in line:
                    logger.info(f"  {line.strip()}")
        except Exception as e:
            logger.error(f"防火墙检查失败: {e}")
    
    def generate_solution_report(self):
        """生成解决方案报告"""
        logger.info("=== 解决方案建议 ===")
        
        solutions = [
            "1. 确保WebSocket服务器正在运行: python websocket_server.py",
            "2. 检查Android设备是否正确连接: adb devices",
            "3. 确保手机和电脑在同一网络",
            "4. 检查防火墙是否阻止了8080端口",
            "5. 如果使用模拟器，确保使用正确的IP地址",
            "6. 检查Android应用的网络权限",
            "7. 查看应用日志: adb logcat | grep MyApplication"
        ]
        
        for solution in solutions:
            logger.info(solution)
    
    async def run_full_diagnostic(self):
        """运行完整诊断"""
        logger.info("🚀 开始数据传输诊断...")
        logger.info(f"服务器地址: {self.server_url}")
        logger.info("=" * 50)
        
        # 网络连接性检查
        network_ok = self.check_network_connectivity()
        
        # WebSocket服务器测试
        websocket_ok = await self.test_websocket_server()
        
        # Android设备检查
        android_ok = self.check_android_device()
        
        # 防火墙检查
        self.check_firewall()
        
        # 生成报告
        logger.info("=" * 50)
        logger.info("📊 诊断结果汇总:")
        logger.info(f"网络连接: {'✅ 正常' if network_ok else '❌ 异常'}")
        logger.info(f"WebSocket服务器: {'✅ 正常' if websocket_ok else '❌ 异常'}")
        logger.info(f"Android设备: {'✅ 正常' if android_ok else '❌ 异常'}")
        
        if network_ok and websocket_ok and android_ok:
            logger.info("🎉 所有检查都通过！数据传输应该正常工作")
        else:
            logger.info("⚠️ 发现问题，请参考以下解决方案:")
            self.generate_solution_report()

async def main():
    diagnostic = DataTransmissionDiagnostic()
    await diagnostic.run_full_diagnostic()

if __name__ == "__main__":
    asyncio.run(main()) 